package com.sh.dc.controller;

import cn.hutool.core.bean.BeanUtil;
import com.sh.dc.common.BaseResult;
import com.sh.dc.common.enums.BizCodeEnum;
import com.sh.dc.common.enums.ValueTypeEnum;
import com.sh.dc.common.pojo.bo.EnumBO;
import com.sh.dc.common.pojo.bo.ParamSaveBO;
import com.sh.dc.common.pojo.query.ParamPageQuery;
import com.sh.dc.entity.Param;
import com.sh.dc.service.IParamService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 参数 前端控制器
 * </p>
 *
 * @author zhenlan
 * @since 2024-07-11
 */
@RestController
@RequestMapping("/param")
public class ParamController {

    @Autowired
    private IParamService paramService;

    @GetMapping("valueTypes")
    public BaseResult valueTypes() {
        List<EnumBO> ret = new ArrayList<>();
        for (ValueTypeEnum valueType : ValueTypeEnum.values()) {
            ret.add(new EnumBO(valueType.getMessage(), valueType.getCode()));
        }
        return BaseResult.success(ret);
    }

    @PostMapping("/save")
    public BaseResult save(@Valid @RequestBody ParamSaveBO saveBO) {
        if (saveBO.getId() == null && paramService.paramNameExisted(saveBO.getName())) {
            return BaseResult.fail(BizCodeEnum.PARAM_NAME_EXISTED);
        }
        Param param = new Param();
        BeanUtil.copyProperties(saveBO, param);
        param.setUpdateTime(new Date());
        return BaseResult.success(paramService.saveOrUpdate(param));
    }

    @PostMapping("/delete/{id}")
    public BaseResult delete(@PathVariable("id") Long id) {
        return BaseResult.success(paramService.removeById(id));
    }

    @GetMapping("/{id}")
    public BaseResult getById(@PathVariable("id") Long id) {
        return BaseResult.success(paramService.getById(id));
    }

    @PostMapping("/page")
    public BaseResult page(@Valid @RequestBody ParamPageQuery query) {
        return BaseResult.success(paramService.queryParamPage(query));
    }

}
